//
//  HomePageViewController.m
//  ShowYork
//
//  Created by hxh on 2020/8/24.
//  Copyright © 2020 hxh. All rights reserved.
//

#import "HomePageRecommendListViewController.h"
#import "HomePageDetailViewController.h"
#import "RPAppUpdateView.h"
#import "UpdateVersionModel.h"
#import "LessonUseageModel.h"
#import "ExercisesPageModel.h"
#import "HomePageItemModel.h"
#import "HomePageNavModel.h"
#import "HomePageRefreshHeader.h"
#import "WaterFallLayout.h"
#import "HomePageItemCell.h"
@interface HomePageRecommendListViewController ()<UIScrollViewDelegate,WaterFallLayoutDelegate,UICollectionViewDelegate,UICollectionViewDataSource,HomePageItemCellDelegate>
@property (nonatomic,strong)UICollectionView *collectionView;

@property (nonatomic,strong)NSMutableArray *dataArray;

@property (nonatomic,strong)NSMutableArray *systemDataArray;

@property (nonatomic,assign)NSInteger page;

//@property (nonatomic,assign)BOOL lastPage;

@property (nonatomic,strong)NSNumber *tagId;

@property (nonatomic,strong)UIView *noDataView;

@property (nonatomic,strong)UIImageView *noDataImgView;

@property (nonatomic,strong)UILabel *noDateLb;

@property (nonatomic,strong)UIButton *noDataBtn;

@property (nonatomic,strong)NSURLSessionTask *task;

@property (nonatomic,strong)NSURLSessionTask *task1;

@property (nonatomic,strong)UIActivityIndicatorView *spin;

@property (nonatomic,strong)UIView *refreshView;

@property (nonatomic,assign)BOOL totalPage;

@end

@implementation HomePageRecommendListViewController


- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
    
    
    
//    [self.navigationController setNavigationBarHidden:YES animated:animated];

}

- (NSMutableArray *)dataArray{
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


- (NSMutableArray *)systemDataArray{
    if (!_systemDataArray) {
        _systemDataArray = [NSMutableArray array];
    }
    return _systemDataArray;
}


- (instancetype)initWithTagId:(NSNumber *)tagId{
    if (self = [super init]) {
        self.tagId = tagId;
    }
    return self;
}


- (void)requestData{
    
    [self.collectionView setContentOffset:CGPointZero];
    
    self.page = 1;
    
    [self showDataLoadState];
    
    [self loadListDataSource];
    
    
}

- (void)reloadDataWithDeleteItem:(HomePageItemModel *)item{
    __block NSInteger index = -1;
    [self.dataArray enumerateObjectsUsingBlock:^(HomePageItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.postId isEqualToNumber:item.postId]) {
            index = idx;
            *stop = YES;
        }
    }];
    if (index != -1) {
        [self.dataArray removeObjectAtIndex:index];
        [self.collectionView reloadData];
    }
}
- (void)reloadItemFollowType:(NSNumber *)followType userId:(NSNumber *)userId{
    [self.dataArray enumerateObjectsUsingBlock:^(HomePageItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.userId isEqualToNumber:userId]) {
            obj.followType = followType;
        }
    }];
    [self.collectionView reloadData];
}

- (void)reloadData{
    [self.collectionView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];

    self.page = 1;
            
    [self setUI];
    
    // Do any additional setup after loading the view.
}

- (void)setUI{
    
    _spin = [[UIActivityIndicatorView alloc] initWithFrame:(CGRect){0,0,40,40}];
    _spin.center = CGPointMake(kScreenW / 2.0f, kScreenH / 3.0);
    _spin.color = [UIColor lightGrayColor];
    _spin.hidesWhenStopped = YES;
        
    WaterFallLayout *layout = [[WaterFallLayout alloc]init];
    layout.delegate = self;
    layout.minimumLineSpacing = 5.0f;
    layout.minimumInteritemSpacing = 5.0f;
    layout.sectionInset = UIEdgeInsetsMake(0, 5, 0, 5);

    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectZero collectionViewLayout:layout];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.collectionView];
    
    [self.collectionView registerClass:[HomePageItemCell class] forCellWithReuseIdentifier:@"HomePageItemCell"];
    
    [self.collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
    __weak typeof(self)weakSelf = self;
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page = 1;
        [weakSelf loadListDataSource];
    }];
    self.collectionView.mj_header = header;
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [MobClick event:@"homePage_footer_refresh"];
    
        weakSelf.page++;
        [weakSelf loadUserListSource];
    }];
    [footer setTitle:@"—— 没有更多了 ——" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = font(10);
    footer.stateLabel.textColor = RGBA(153, 153, 153, 1);
    footer.hidden = YES;
    self.collectionView.mj_footer = footer;
    
    self.noDataView = [[UIView alloc]init];
    self.noDataView.hidden = YES;
    [self.view addSubview:self.noDataView];
    
    [self.noDataView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
   
    self.noDataImgView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"mine_noList_tag"]];
    [self.noDataView addSubview:self.noDataImgView];
    
    [self.noDataImgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(self.view).offset(-kNavBarHeight);
        make.centerX.equalTo(self.view);
    }];
    
    self.noDateLb = [[UILabel alloc]init];
    self.noDateLb.text = @"无内容";
    self.noDateLb.textColor = C153;
    self.noDateLb.font = font(12);
    self.noDateLb.textAlignment = NSTextAlignmentCenter;
    [self.noDataView addSubview:self.noDateLb];
    [self.noDateLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.noDataView);
        make.top.equalTo(self.noDataImgView.mas_bottom).offset(12);
    }];
    
    
    UIView *v2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, kScreenH)];
    v2.backgroundColor = RGBA(248, 248, 248, 1);
    
    UIView *v3 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 120)];
    v3.backgroundColor = [UIColor whiteColor];
    
    self.refreshView = v3;
    
    [v2 addSubview:v3];

    v2.layer.zPosition = -2;
    self.collectionView.backgroundView = v2;
    

    UIView *v = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenW, 120)];
    v.layer.zPosition = -1;
    v.userInteractionEnabled = NO;
    CAGradientLayer *leftLayer = [CAGradientLayer layer];
    leftLayer.frame = v.bounds;
    leftLayer.colors = @[(id)RGBA(255, 255, 255, 1).CGColor,(id)RGBA(248, 248, 248, 1).CGColor];
    [v.layer addSublayer:leftLayer];
    
    
    [self.collectionView insertSubview:v atIndex:0];
    self.collectionView.backgroundColor = RGBA(248, 248, 248, 1);
}

- (void)showDataLoadState{
    [self.view addSubview:_spin];
    [_spin startAnimating];
}

- (void)hideDataLoadLoadState{
    if(_spin.isAnimating){
        [_spin stopAnimating];
    }
}


- (void)loadListDataSource{
    
    dispatch_group_t group = dispatch_group_create();
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self loadSystemListSource];
    });
    dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self loadUserListSource];
    });
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
      
        [self hideDataLoadLoadState];
        
        [self.systemDataArray enumerateObjectsUsingBlock:^(HomePageItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            __block NSInteger index = -1;
            [self.dataArray enumerateObjectsUsingBlock:^(HomePageItemModel *_Nonnull subObject, NSUInteger subIndex, BOOL * _Nonnull stop) {
                if([subObject.postId isEqualToNumber:obj.postId]){
                    index = subIndex;
                    *stop = YES;
                }
            }];
            
            if (index != -1) {
                [self.dataArray removeObjectAtIndex:index];
            }
            
            [self.dataArray insertObject:obj atIndex:idx];
        }];
        
        if ([self.collectionView.mj_header isRefreshing]) {
            [self.collectionView.mj_header endRefreshing];
        }
        if ([self.collectionView.mj_footer isRefreshing]) {
            [self.collectionView.mj_footer endRefreshing];
        }
        
        [self dealCollectionFooterTitle];
        
        [self.collectionView reloadData];
        
        self.collectionView.mj_footer.hidden = self.dataArray.count == 0;
        self.noDataView.hidden = self.dataArray.count > 0;

    });
}

- (void)loadSystemListSource{
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"tagId"] = self.tagId;
    param[@"md5"] =  [RPAppManager md5StrWithApi:GetOfficialPostDetailList];
    param[@"type"] = @"2";
    [[RPNetworkExtensionTool sharedTool]requestPOST:kGET_REQUEST_URL(GetOfficialPostDetailList) parames:param success:^(id responseObj) {
        self.systemDataArray = [HomePageItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE]];
        dispatch_semaphore_signal(sema);
    } failure:^(id error) {
        dispatch_semaphore_signal(sema);
    }];
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    
}

- (void)loadUserListSource{
    
    dispatch_semaphore_t sema = dispatch_semaphore_create(0);
    if (self.page > 1) {
        sema = dispatch_semaphore_create(1);
    }
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"pageIndex"] = @(self.page);
    param[@"pageSize"] = @(10);
    param[@"tagId"] = self.tagId;
    param[@"type"] = @"2";
    param[@"md5"] = [RPAppManager md5StrWithApi:GetIndexPostList];
    [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(GetIndexPostList) parames:param success:^(id responseObj) {
        if ([self.collectionView.mj_footer isRefreshing]) {
            [self.collectionView.mj_footer endRefreshing];
        }
        if (self.page == 1) {
            self.dataArray = [HomePageItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]];
        }else{
            [self.dataArray addObjectsFromArray:[HomePageItemModel mj_objectArrayWithKeyValuesArray:responseObj[RESPONSE][LIST]]];
            
        }
        
        if ([responseObj[RESPONSE][LASTPAGE] boolValue] || ![responseObj[RESPONSE][NEXTPAGE]boolValue]) {
            [self.collectionView.mj_footer endRefreshingWithNoMoreData];
            self.totalPage = YES;
        }else{
            [self.collectionView.mj_footer resetNoMoreData];
            self.totalPage = NO;
        }
        if (self.page > 1) {
            [self dealCollectionFooterTitle];
            [self.collectionView reloadData];
        }
        
        dispatch_semaphore_signal(sema);
    } failure:^(id error) {
        self.page--;
        dispatch_semaphore_signal(sema);
    }];
    dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}

- (void)dealCollectionFooterTitle{
    CGFloat bottom = self.collectionView.mj_insetB;
    if (self.totalPage) {
        if (self.collectionView.mj_footer.cl_height == 44.0f) {
            self.collectionView.mj_footer.cl_height = 138.0f;
            if (bottom == 44.0f || bottom == GK_SAVEAREA_BTM + 44.0f) {
                self.collectionView.mj_insetB = 138.0f;
            }
        }
    }else{
        if (self.collectionView.mj_footer.cl_height == 138.0f) {
            self.collectionView.mj_footer.cl_height = 44.0f;
            if (bottom == 138.0f) {
                self.collectionView.mj_insetB = 44.0f;
            }
        }
    }
}



- (CGFloat)flowLayout:(UICollectionViewLayout *)layout heightForIndexPath:(NSIndexPath *)indexPath{
    
    HomePageItemModel *itemModel = self.dataArray[indexPath.item];
    
    CGFloat screenW = UIScreen.mainScreen.bounds.size.width;
    // 计算一半的宽度占比
    CGFloat itemW = (screenW - 3 * 5)/2;
    // 计算图片的高度3/4
    CGFloat imgH = itemW/3*4;
    
    CGSize textSize = [self getTextSizeWithText:itemModel.contentText font:[UIFont systemFontOfSize:12] maxSize:CGSizeMake(itemW - 16, MAXFLOAT)];
    
   
    if (itemModel.contentType.intValue == 1) {
        return imgH + 42;
    }else{
        if (itemModel.contentText.length == 0) {
            return imgH + 42;
        }else{
            CGFloat maxH = [self heightOfLines:2 font:[UIFont systemFontOfSize:12]];
            return imgH + MIN(ceil(textSize.height),maxH) + 12 + 40;
        }
    }
}

- (CGFloat)heightOfLines:(int)lines font:(UIFont *)font{
    if (lines <= 0) {
        return 0;
    }
    NSString *str = @"*";
    for (int index = 0; index < lines - 1 ; index++) {
        str = [str stringByAppendingString:@"\n*"];
    }
    NSDictionary *dict = @{NSFontAttributeName:font};
    
    CGSize size = [str sizeWithAttributes:dict];
    
    return ceil(size.height);
}

- (CGSize)getTextSizeWithText:(NSString *)text font:(UIFont *)font maxSize:(CGSize)maxSize
{
    CGSize size = CGSizeZero;
    if(text == nil){
        text = @"";
    }
    if(font == nil){
        font = [UIFont systemFontOfSize:13];
    }
    NSDictionary *attribute = [NSDictionary dictionaryWithObjectsAndKeys:font, NSFontAttributeName,nil];
    size = [text boundingRectWithSize:maxSize options: NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading attributes:attribute context:nil].size;
    return size;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.dataArray.count;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HomePageItemCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"HomePageItemCell" forIndexPath:indexPath];
    cell.delegate = self;
    [cell setItemModel:self.dataArray[indexPath.item]];
    return cell;
}


- (void)doLikeWithItemModel:(HomePageItemModel *)itemModel{
    if (![RPAppManager isLogin]) {
        [MGJRouter openURL:@"local://ddup/unLogin" withUserInfo:@{@"navigationVC":self.navigationController} completion:nil];
        return;
    }
    
    [self.task cancel];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userId"] = [RPAppManager getCustomerId];
    param[@"type"] = @1;
    param[@"postId"] = itemModel.postId;
    param[@"isTourist"] = itemModel.isLike?@1:@2;
    param[@"md5"] = [RPAppManager md5StrWithApi:DoDetailLike];
    self.task = [[RPNetworkExtensionTool sharedTool] requestPOST:kGET_REQUEST_URL(DoDetailLike) parames:param success:^(id responseObj) {
        
    } failure:^(NSError *error) {
        [WHToast showMessage:error.userInfo[@"info"] duration:2 finishHandler:nil];
        NSInteger likeNum = itemModel.likeNum.intValue;
        if (itemModel.isLike) {
            likeNum--;
          
        }else{
            likeNum++;
        }
        itemModel.likeNum = @(likeNum);
        itemModel.isLike = !itemModel.isLike;
        [self.collectionView reloadData];
    }];
    
}

- (void)showPageDettailWithItemModel:(HomePageItemModel *)itemModel{
    NSInteger index = [self.dataArray indexOfObject:itemModel];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[kXHItemType] = @(XHPageDetailItemTypeNormal);
    param[kXHPlatformType] = @(XHPageDetailPlatformTypeNormal);
    param[kXHShowUserInfo] = @(YES);
    param[kXHCurrentPage] = @(self.page);
    param[kXHCurrentIndex] = @(index);
    param[kXHDetailTagId] = self.tagId;
    param[kXHListSource] = self.dataArray;
    param[kXHHeaderHidden] = @(YES);
    HomePageDetailViewController *dtlVC = [[HomePageDetailViewController alloc]initWithConfigInfo:param];
    [self.navigationController pushViewController:dtlVC animated:YES];
    
}
- (void)showUserInfoById:(NSNumber *)userId{
    
    [MGJRouter openURL:@"local://ddup/homePage/userInfo" withUserInfo:@{@"navigationVC":self.navigationController,@"userId":userId,@"loadType":@(1)} completion:nil];
}



- (void)updateItemWithCurrentModel:(HomePageItemModel *)itemModel{
    
    
    [self.dataArray enumerateObjectsUsingBlock:^(HomePageItemModel *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj.userId isEqualToNumber:itemModel.userId]) {
            obj.followType = itemModel.followType;
            if ([obj.postId isEqualToNumber:itemModel.postId]) {
                obj.watchNum = itemModel.watchNum;
                obj.shareNum = itemModel.shareNum;
                obj.likeNum = itemModel.likeNum;
                obj.unlikeNum = itemModel.unlikeNum;
                obj.isLike = itemModel.isLike;
                obj.isUnLike = itemModel.isUnLike;
            }
        }
    }];
    [self.collectionView reloadData];
}

- (void)reloadTargetItemWithCurrentModel:(HomePageItemModel *)itemModel{
    [self updateItemWithCurrentModel:itemModel];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (scrollView.contentOffset.y <= 0) {
        self.refreshView.frame = CGRectMake(0,scrollView.contentOffset.y,kScreenW,-(scrollView.contentOffset.y * 2) + 120);
        self.refreshView.hidden = NO;
    }else{
        self.refreshView.hidden = YES;
    }
}


@end
